<!--
 * @Author: AuroCaffe 18509564594@163.com
 * @Date: 2025-05-19 15:13:38
 * @LastEditors: AuroCaffe 18509564594@163.com
 * @LastEditTime: 2025-08-01 10:14:23
 * @FilePath: \HuiLin\pages\mePages\balance\Withdrawal.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
	<view class="withdrawal-page">
		<!-- 自定义头部 -->
		<headerSlot :propsColor="'#fff'">
			<template v-slot:header>
				<view class="header-container">
					<view class="back-btn" @click="closePage()">
						<text class="cuIcon-back"></text>
					</view>
					<view class="page-title">
						佣金提现
					</view>
					<view class="records-btn" @click="goToRecords">
						<text class="cuIcon-list"></text>
					</view>
				</view>
			</template>
		</headerSlot>

		<!-- 主要内容区域 -->
		<view class="content-container">
			<!-- 佣金信息卡片 -->
			<view class="balance-card">
				<view class="balance-header">
					<view class="balance-icon">
						<text class="cuIcon-moneybag"></text>
					</view>
					<view class="balance-info">
						<view class="balance-label">账户佣金</view>
						<view class="balance-amount">￥{{formatAmount(balance)}}</view>
					</view>
				</view>
			</view>

			<!-- 提现规则 -->
			<view class="rules-card">
				<view class="rules-header">
					<text class="rules-title">提现规则</text>
				</view>
				<view class="rules-list">
					<view class="rule-item" v-for="(rule, index) in withdrawalRules" :key="index">
						<view class="rule-dot">•</view>
						<text class="rule-text">{{rule}}</text>
					</view>
				</view>
			</view>

			<!-- 提现表单 -->
			<view class="form-card">
				<view class="form-header">
					<text class="form-title">提现金额</text>
				</view>

				<!-- 金额输入 -->
				<view class="amount-input-container">
					<view class="input-wrapper">
						<text class="currency-symbol">￥</text>
						<input type="number" class="amount-input" placeholder="请输入10-1000之间的整数" v-model="balanceValue"
							@input="handleInput" maxlength="4" :disabled="submitting" />
					</view>
					<view class="all-amount-btn" @click="allBalance" :class="{ disabled: submitting }">
						全部
					</view>
				</view>

				<!-- 错误提示 -->
				<view v-if="showError" class="error-container">
					<text class="error-icon">!</text>
					<text class="error-text">{{errorMessage}}</text>
				</view>

				<!-- 快捷金额 -->
				<view class="quick-amounts">
					<view class="quick-item" v-for="amount in quickAmounts" :key="amount"
						@click="selectQuickAmount(amount)"
						:class="{ active: balanceValue == amount, disabled: submitting }">
						￥{{amount}}
					</view>
				</view>

				<!-- 操作按钮 -->
				<view class="action-buttons">
					<button class="contact-btn" open-type="contact" :disabled="submitting">
						联系客服
					</button>
					<button class="withdraw-btn" :class="{ disabled: !isValid || submitting }"
						:disabled="!isValid || submitting" @click="handleWithdraw">
						<text v-if="submitting" class="loading-text">处理中...</text>
						<text v-else>{{isValid ? '立即提现' : '金额不符合要求'}}</text>
					</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import headerSlot from '@/components/header-slot.vue';
	import {
		applyWithdraw,
		updateUserSubscription
	} from '@/api/withdraw.js';
	import Storage from '@/utils/storage.js';
	import {
		subscribeWithdrawMessages
	} from '@/utils/wechat-subscription.js';
	import {
		getCertificationInfo
	} from '@/api/mine.js';

	export default {
		components: {
			headerSlot,
		},
		data() {
			return {
				balance: 0,
				balanceValue: '',
				isValid: false,
				showError: false,
				errorMessage: '',
				submitting: false,
				withdrawConfig: {
					minAmount: 1,
					maxAmount: 1000,
					dailyLimit: 2,
					fee: {
						under100: 0,
						over100: 0
					}
				},
				withdrawalRules: [
					'佣金提现需要业主认证信息与微信实名认证信息一致',
					'单笔提现最低10元，最多200元，每天可提现10次',
					'仅限整数提交，请勿填写如：99.99 或 99.9',
					'提现申请将在1-3个工作日内到账',
					'提现到微信佣金，请注意查收',
					'如有疑问，请联系客服咨询'
				],
				quickAmounts: [50, 100, 200, 500],
				userInfo: null,
				authInfo: null, // 认证信息
				hasShownCertificationModal: false // 是否已显示认证弹窗
			};
		},
		async onLoad(opt) {
			this.balance = Number(opt.balance) || 0
			// 检查业主认证状态
			await this.checkOwnerCertification()
			this.init()
		},

		async onShow() {
			// 获取用户信息
			await this.loadUserInfo()
			// 获取认证信息
			await this.loadAuthInfo()
			// 重新检查业主认证状态（用户可能从认证页面返回）
			await this.checkOwnerCertification()
		},
		methods: {
			closePage() {
				uni.navigateBack()
			},

			goToRecords() {
				this.$router.smartNavigate({
					url: '/pages/mePages/balance/WithdrawRecords'
				})
			},

			init() {
				// 初始化页面
				this.validateAmount()
			},

			// 检查业主认证状态
			async checkOwnerCertification() {
				try {
					// 从本地存储获取用户信息
					const userInfo = Storage.getUserInfo()
					if (!userInfo) {
						console.log('未找到用户信息')
						return
					}

					// 检查是否已进行业主认证
					if (!userInfo.isOwner) {
						// 避免重复显示弹窗
						if (this.hasShownCertificationModal) {
							return
						}

						this.hasShownCertificationModal = true

						// 显示认证提示弹窗
						uni.showModal({
							title: '需要业主认证',
							content: '只有认证业主才能进行佣金提现，请先完成业主认证',
							confirmText: '去认证',
							cancelText: '取消',
							success: (res) => {
								if (res.confirm) {
									// 跳转到业主认证页面
									this.$router.smartNavigate({
										url: '/pages/mePages/certifiedOwners'
									})
								} else {
									// 用户取消，返回上一页
									uni.navigateBack()
								}
							},
							complete: () => {
								// 重置弹窗显示标志
								this.hasShownCertificationModal = false
							}
						})
					}
				} catch (error) {
					console.error('检查业主认证状态失败:', error)
				}
			},

			// 加载用户信息
			async loadUserInfo() {
				try {
					// 从本地存储获取用户信息
					const userInfo = Storage.getUserInfo()
					if (userInfo) {
						this.userInfo = userInfo
					} else {
						console.log('未找到用户信息')
					}
				} catch (error) {
					console.error('获取用户信息失败:', error)
				}
			},

			// 加载认证信息
			async loadAuthInfo() {
				try {
					const response = await getCertificationInfo()
					if (response && response.data && response.data.data) {
						this.authInfo = response.data.data
						console.log('认证信息:', this.authInfo)
					}
				} catch (error) {
					console.error('获取认证信息失败:', error)
				}
			},



			// 输入处理
			handleInput(e) {
				let value = e.detail.value
				this.balanceValue = value
				this.validateAmount()
			},

			// 选择快捷金额
			selectQuickAmount(amount) {
				if (this.submitting) return

				this.balanceValue = amount.toString()
				this.validateAmount()
			},

			// 金额验证
			validateAmount() {
				const num = parseInt(this.balanceValue) || 0

				// 验证规则
				const rules = [{
						test: isNaN(num) || num <= 0,
						msg: '请输入有效的正整数'
					},
					{
						test: num < this.withdrawConfig.minAmount,
						msg: `提现金额需大于${this.withdrawConfig.minAmount}元`
					},
					{
						test: num > this.withdrawConfig.maxAmount,
						msg: `单笔提现金额不可超过${this.withdrawConfig.maxAmount}元`
					},
					{
						test: num > this.balance,
						msg: '提现金额不能超过账户佣金'
					},
					{
						test: !Number.isInteger(num),
						msg: '必须为整数金额'
					}
				]

				// 执行验证
				const error = rules.find(rule => rule.test)

				// 更新状态
				this.isValid = !error
				this.showError = !!error
				this.errorMessage = error ? error.msg : ''
			},

			// 全部提现
			allBalance() {
				if (this.submitting) return

				const balance = Number(this.balance)

				if (isNaN(balance) || balance <= 0) {
					uni.showToast({
						title: '佣金数据异常',
						icon: 'none'
					})
					return
				}

				let integerAmount = Math.floor(balance)

				if (integerAmount < this.withdrawConfig.minAmount) {
					uni.showToast({
						title: `佣金不足${this.withdrawConfig.minAmount}元`,
						icon: 'none'
					})
					return
				}

				if (integerAmount > this.withdrawConfig.maxAmount) {
					integerAmount = this.withdrawConfig.maxAmount
				}

				this.balanceValue = integerAmount.toString()
				this.validateAmount()
			},

			// 提现操作
			async handleWithdraw() {
				if (!this.isValid || this.submitting) return

				// 再次检查业主认证状态
				const userInfo = Storage.getUserInfo()
				if (!userInfo || !userInfo.isOwner) {
					uni.showToast({
						title: '需要业主认证才能提现',
						icon: 'none'
					})
					return
				}

				try {
					this.submitting = true

					uni.showLoading({
						title: '提现处理中...'
					})

					// 获取用户信息
					const userInfo = Storage.getUserInfo()

					// 检查用户信息
					if (!userInfo) {
						throw new Error('请先登录')
					}

					// 检查用户标识，如果没有则使用模拟数据
					const accountNumber = userInfo.openid || userInfo.unionid || userInfo.userId || userInfo.id ||
						'mock_user_001'
					// 优先使用业主认证的实名信息
					const accountName = this.authInfo?.latestAuth?.realName || ''

					console.log('用户信息:', userInfo)
					console.log('认证信息:', this.authInfo)
					console.log('使用的账户信息:', {
						accountNumber,
						accountName
					})

					const amount = parseInt(this.balanceValue)
					const fee = amount >= 100 ? this.withdrawConfig.fee.over100 : this.withdrawConfig.fee.under100
					const actualAmount = amount - fee

					// 构建提现申请数据
					const withdrawData = {
						amount: amount,
						withdrawMethod: 'wechat',
						accountInfo: {
							accountName: accountName,
							accountNumber: accountNumber
						}
					}

					// 调用真实提现API
					const response = await applyWithdraw(withdrawData)

					console.log('提现API响应:', response)

					// 检查响应状态
					if (response && response.data && response.data.success) {
						uni.hideLoading()

						// 订阅微信推送消息
						await this.subscribeWechatMessage()

						// 显示成功信息
						const successMsg = response.data.message || (fee > 0 ?
							`提现申请提交成功，手续费${fee}元，实际到账${actualAmount}元` :
							`提现申请提交成功，预计1-3个工作日到账`)

						uni.showToast({
							title: successMsg,
							icon: 'success',
							duration: 3000
						})

						// 重置表单
						this.balanceValue = ''
						this.validateAmount()

						// 设置提现成功标志，用于通知其他页面刷新
						uni.setStorageSync('withdrawSuccess', Date.now());

						// 延迟返回上一页
						setTimeout(() => {
							uni.navigateBack()
						}, 2000)
					} else {
						const errorMsg = response?.data?.message || response?.message || '提现申请失败'
						console.error('提现API返回错误:', response)
						throw new Error(errorMsg)
					}

				} catch (error) {
					console.error('提现失败:', error)
					console.error('错误详情:', {
						message: error.message,
						stack: error.stack,
						response: error.response
					})
					uni.hideLoading()

					// 显示详细错误信息（开发环境）
					let errorMsg = error.message || '提现失败，请重试'
					if (process.env.NODE_ENV === 'development' && error.response) {
						errorMsg += ` (状态码: ${error.response.statusCode})`
					}

					uni.showToast({
						title: errorMsg,
						icon: 'none',
						duration: 3000
					})
				} finally {
					this.submitting = false
				}
			},

			// 订阅微信推送消息
			async subscribeWechatMessage() {
				try {
					// 使用工具函数订阅提现进度推送
					const result = await subscribeWithdrawMessages()

					console.log('订阅消息结果:', result)

					if (result.success) {
						if (result.hasAccepted) {
							console.log('用户已同意订阅提现进度推送')

							// 保存订阅状态到后端
							await this.saveSubscriptionStatus(true)

							uni.showToast({
								title: '已开启提现进度推送',
								icon: 'success',
								duration: 2000
							})
						} else if (result.hasRejected) {
							console.log('用户拒绝订阅提现进度推送')

							uni.showToast({
								title: '您已拒绝推送通知',
								icon: 'none',
								duration: 2000
							})
						} else if (result.hasBanned) {
							console.log('用户被禁用了订阅消息')

							uni.showToast({
								title: '订阅消息功能被禁用',
								icon: 'none',
								duration: 2000
							})
						}
					} else {
						console.log('订阅消息失败:', result.message)

						// 订阅失败不影响提现流程，只记录日志
						uni.showToast({
							title: '推送订阅失败，但不影响提现',
							icon: 'none',
							duration: 2000
						})
					}
				} catch (error) {
					console.error('订阅消息失败:', error)

					// 订阅失败不影响提现流程，只记录日志
					uni.showToast({
						title: '推送订阅失败，但不影响提现',
						icon: 'none',
						duration: 2000
					})
				}
			},

			// 保存订阅状态到后端
			async saveSubscriptionStatus(isSubscribed) {
				try {
					if (!this.userInfo || !this.userInfo.id) {
						console.log('用户信息不完整，跳过保存订阅状态')
						return
					}

					const response = await updateUserSubscription({
						userId: this.userInfo.id,
						withdrawNotification: isSubscribed
					})

					if (response.success) {
						console.log('订阅状态已保存:', isSubscribed)
					} else {
						console.error('保存订阅状态失败:', response.message)
					}
				} catch (error) {
					console.error('保存订阅状态失败:', error)
				}
			},

			formatAmount(amount) {
				if (!amount && amount !== 0) return '0.00'
				return Number(amount).toFixed(2)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.withdrawal-page {
		min-height: 100vh;
		background: #f5f7fa;
	}

	.header-container {
		display: flex;
		align-items: center;
		padding: 0 32rpx;
		width: 100%;
		height: 88rpx;

		.back-btn {
			margin-right: 20rpx;
			padding: 8rpx;

			.cuIcon-back {
				font-size: 36rpx;
				color: #2C2622;
			}
		}

		.page-title {
			flex: 1;
			font-weight: 600;
			font-size: 36rpx;
			color: #2C2622;
			text-align: center;
		}

		.records-btn {
			padding: 8rpx;

			.cuIcon-list {
				font-size: 36rpx;
				color: #2C2622;
			}
		}
	}

	.content-container {
		padding: 32rpx;
	}

	.balance-card {
		background: linear-gradient(135deg, #FE6100 0%, #FF6B35 100%);
		border-radius: 20rpx;
		padding: 32rpx 24rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(254, 97, 0, 0.3);

		.balance-header {
			display: flex;
			align-items: center;

			.balance-icon {
				width: 64rpx;
				height: 64rpx;
				background: rgba(255, 255, 255, 0.2);
				border-radius: 16rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-right: 24rpx;

				.cuIcon-moneybag {
					font-size: 32rpx;
					color: #FFFFFF;
				}
			}

			.balance-info {
				flex: 1;

				.balance-label {
					font-size: 28rpx;
					color: rgba(255, 255, 255, 0.9);
					margin-bottom: 8rpx;
				}

				.balance-amount {
					font-size: 48rpx;
					color: #FFFFFF;
					font-weight: 700;
				}
			}
		}
	}

	.rules-card {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 32rpx 24rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

		.rules-header {
			margin-bottom: 24rpx;

			.rules-title {
				font-size: 32rpx;
				color: #2C2622;
				font-weight: 600;
			}
		}

		.rules-list {
			.rule-item {
				display: flex;
				align-items: flex-start;
				margin-bottom: 16rpx;

				&:last-child {
					margin-bottom: 0;
				}

				.rule-dot {
					font-size: 32rpx;
					color: #FE6100;
					margin-right: 16rpx;
					line-height: 1.4;
				}

				.rule-text {
					flex: 1;
					font-size: 28rpx;
					color: #606266;
					line-height: 1.5;
				}
			}
		}
	}

	.form-card {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 32rpx 24rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

		.form-header {
			margin-bottom: 32rpx;

			.form-title {
				font-size: 32rpx;
				color: #2C2622;
				font-weight: 600;
			}
		}

		.amount-input-container {
			display: flex;
			align-items: center;
			margin-bottom: 24rpx;

			.input-wrapper {
				flex: 1;
				display: flex;
				align-items: center;
				background: #f8f9fa;
				border-radius: 16rpx;
				padding: 24rpx;
				margin-right: 24rpx;

				.currency-symbol {
					font-size: 36rpx;
					color: #2C2622;
					font-weight: 600;
					margin-right: 16rpx;
				}

				.amount-input {
					flex: 1;
					font-size: 36rpx;
					color: #2C2622;
					font-weight: 600;
					background: transparent;
					border: none;
					outline: none;
				}
			}

			.all-amount-btn {
				padding: 24rpx 32rpx;
				background: linear-gradient(135deg, #FE6100 0%, #FF6B35 100%);
				color: #FFFFFF;
				border-radius: 16rpx;
				font-size: 28rpx;
				font-weight: 600;
				transition: opacity 0.2s;

				&:active {
					opacity: 0.8;
				}

				&.disabled {
					opacity: 0.5;
				}
			}
		}

		.error-container {
			display: flex;
			align-items: center;
			background: #fef0f0;
			border: 1rpx solid #fbc4c4;
			border-radius: 12rpx;
			padding: 16rpx 20rpx;
			margin-bottom: 24rpx;

			.error-icon {
				width: 32rpx;
				height: 32rpx;
				background: #f56c6c;
				color: #FFFFFF;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 20rpx;
				font-weight: bold;
				margin-right: 16rpx;
			}

			.error-text {
				flex: 1;
				font-size: 28rpx;
				color: #f56c6c;
			}
		}

		.quick-amounts {
			display: flex;
			flex-wrap: wrap;
			gap: 16rpx;
			margin-bottom: 48rpx;

			.quick-item {
				padding: 20rpx 32rpx;
				background: #f8f9fa;
				border: 2rpx solid #e9ecef;
				border-radius: 16rpx;
				font-size: 28rpx;
				color: #606266;
				transition: all 0.2s;

				&:active {
					transform: scale(0.95);
				}

				&.active {
					background: linear-gradient(135deg, #FE6100 0%, #FF6B35 100%);
					border-color: #FE6100;
					color: #FFFFFF;
				}

				&.disabled {
					opacity: 0.5;
				}
			}
		}

		.action-buttons {
			display: flex;
			gap: 24rpx;

			.contact-btn,
			.withdraw-btn {
				flex: 1;
				height: 88rpx;
				border-radius: 16rpx;
				font-size: 32rpx;
				font-weight: 600;
				display: flex;
				align-items: center;
				justify-content: center;
				transition: all 0.2s;
			}

			.contact-btn {
				background: #f8f9fa;
				color: #606266;
				border: 2rpx solid #e9ecef;

				&:active {
					background: #e9ecef;
				}
			}

			.withdraw-btn {
				background: linear-gradient(135deg, #FE6100 0%, #FF6B35 100%);
				color: #FFFFFF;
				border: none;

				&:active {
					transform: scale(0.98);
				}

				&.disabled {
					background: #c0c4cc;
					opacity: 0.6;
				}

				.loading-text {
					display: flex;
					align-items: center;

					&::before {
						content: '';
						width: 24rpx;
						height: 24rpx;
						border: 2rpx solid #FFFFFF;
						border-top: 2rpx solid transparent;
						border-radius: 50%;
						animation: spin 1s linear infinite;
						margin-right: 12rpx;
					}
				}
			}
		}
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>